<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Http\Requests;
use App\Link;
use App\Medal;
use App\Message;
use App\Parsedown;
use App\Solve;
use App\Study;
use App\Task;
use App\User;
use App\Utils;
use App\Permission;
use Auth;
use DB;
use Illuminate\Http\Request;
use Log;

class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function id2url(Request $request, $id)
    {
		return "<a href=http://www.qlcoder.com/task/".Utils::id2url($id).">url</a>";

    }

    public function url2id(Request $request, $id)
    {
        return Utils::url2id($id);
    }

    public function index()
    {
        $fr = fopen("/home/xingshi/admin_calc.html", "r");
        while (!feof($fr)) {
            echo fgetc($fr);
        }
        fclose($fr);
    }

    public function index2()
    {
        if (!Auth::check()) return;
        if (Auth::user()->id != 19) return;
        $extrat = array(25, 41, 72, 73, 76, 95, 140);
        $uextrats = array();
        foreach ($extrat as $t) {
            //41 72
            if ($t == 25 || $t == 95)
                $arr = DB::select("select max(score) as s,userid,id from solves where type=0 and taskid=" . $t . " group by userid order by s desc");
            else
                $arr = DB::select("select min(score) as s,userid,id from solves where type=0 and taskid=" . $t . " group by userid order by s asc");
            $sz = count($arr);
            $s = 500;
            for ($i = 0; $i < $sz;) {
                $ts = 0;
                for ($j = $i; $j < $sz; $j++) {
                    if ($arr[$i]->s != $arr[$j]->s) break;
                    $ts += $s;
                    $s /= 2;
                }
                $num = $j - $i;
                for ($k = $i; $k < $j; $k++) {
                    $rs = intval($ts / $num * 100);
                    if ($rs < 100) $rs = 100;
                    $str = "update solves set rscore=" . $rs . " where id=" . $arr[$k]->id . " limit 1";
                    $data = DB::update("update solves set rscore=" . $rs . " where id=" . $arr[$k]->id . " limit 1");
                    $uid = $arr[$k]->userid;
                    if (!isset($uextrats[$uid])) $uextrats[$uid] = 0;
                    $uextrats[$uid] += $rs;
                }
                $i = $j;
            }
        }
        Log::info("admin page");
        $ucnt = User::count();
        $scnt = Solve::count();
        $sccnt = Solve::where('type', '=', 0)->count();

        //
        echo("用户数:" . ($ucnt - 16) . "\n<br>");
        echo("解题尝试次数:" . $scnt . "\n<br>");
        echo("解题正确次数:" . $sccnt . "\n<br>");

        $tasks = array();

        $t1 = time();
        for ($i = 1; $i <= 125; $i++) {
            if ($i == 104) continue;
            if ($i == 72 || $i == 73 || $i == 25 || $i == 41 || $i == 76 || $i == 95) continue;
            $task = Task::find($i);
            $cnta = DB::select("select count(distinct userid) as cc from solves where type=0 and taskid=" . $i);
            $cnt = $cnta[0]->cc;
            if ($cnt > 0) $cnt -= 1;
            if ($cnt == 0) $score = 1000;
            else $score = 1000 / $cnt;
            if ($score < 1) $score = 1;
            if ($i == 36 || $i == 69) $score = 0;
            $task->score = (int)($score * 100);
            $task->save();
            $tasks[$i] = $task->score;
            $cntb = DB::select("select count(distinct userid) as cc from solves where taskid=" . $i);
            $cnt2 = $cntb[0]->cc;
            echo("第" . $i . "题<a href='#'> [" . $task->title . "]</a> 做出来的人数:" . $cnt . '/' . ($cnt + $cnt2) . ' 分数:' . $score . '<br>');
        }
        $t2 = time();
        $users = User::all()->sortbyDesc('score');
        $rank = 0;
        foreach ($users as $user) {
            if (Permission::userid_is_norank($user->id)) continue;
            $rank++;
            $s = 0;
            $solves = Solve::whereUseridAndType($user->id, 0)->groupby("taskid")->get();
            $tcnt = 0;
            foreach ($solves as $solve) {
                $i = $solve->taskid;
                if ($i == 72 || $i == 73 || $i == 25 || $i == 41 || $i == 76 || $i == 95) continue;
                if ($solve->taskid == 69 || $solve->taskid == 36) continue;
                $tcnt++;
                if ($solve->taskid == 44) {
                    $s += $solve['score'] * 100;
                } else if ($solve->taskid == 80) {
                    $s += $solve['score'] * ($solve['score'] + 1) * 25;
                } else
                    $s += $tasks[$solve->taskid];
            }
            if ($s == 0) continue;
            if (isset($uextrats[$user->id]))
                $s += $uextrats[$user->id];

            $user->score = $s;
            $user->solveNum = $tcnt;
            var_dump($rank);
            $user->rank = $rank;
            $user->save();
            echo $user->id . ' <font color="red">' . $user->name . "</font> " . date("Y-m-d H:i:s", $user->last_login_time);
            echo '<a href="/u/' . Utils::id2url($user->id) . '">' . ($s / 100) . "</a><br>";
        }
        $t3 = time();
        var_dump($t3 - $t2);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function upstudy(Request $request)
    {
        $input = $request->all();
        $comment = Study::find($input["id"]);

        $comment->type = 1 - $comment->type;
        $comment->save();
        echo "设置成功 ";
    }

    public function dels(Request $request)
    {
        $input = $request->all();
        $comment = Study::find($input["id"]);

        $comment->delete = 1;
        $comment->save();
        echo "删除成功 ";
    }

    public function del(Request $request)
    {
        $input = $request->all();
        $comment = Comment::find($input["id"]);

        $comment->delete = 1;
        $comment->save();
        echo "删除成功 ";
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return Response
     */
    public function sender(Request $request)
    {
        $id = 22;
        $t = Task::find($id);
        $links = Link::whereFirst($id)->get();
        if (count($links) != 0) {
            $content = "恭喜你,正确的解答了task " . $id . " ***" . $t->title . "*** ，你的技能树已扩展，以下是解锁的新task列表:\n\n";
            foreach ($links as $link) {
                var_dump($link->second);
                $task = Task::find($link->second);
                $content .= "* [" . $task->title . "](http://www.qlcoder.com/task/" . Utils::id2url($task->id) . ")\n";

            }
            $content .= "\n赶紧回到[首页](http://www.qlcoder.com/home)学习新的技能点吧。";
        } else {
            $content = "恭喜你,正确的解答了task " . $id . " ***" . $t->title . "***，好厉害！\n\n你已经做到了技能树的最末端了，我们正在加紧后续task的审核，同时也欢迎贡献新的task。";
        }
        var_dump($content);
        if ($request->isMethod('post')) {
            $input = $request->all();
            $data = array();
            $data['senderid'] = 1;
            $data['receiverid'] = $input['userid'];
            $user = User::find($input['userid']);
            $user->msgcnt += 1;
            $user->save();
            $Parsedown = new Parsedown();
            //$data['content']=$Parsedown->text($input['content']);
            $data['content'] = $Parsedown->text($content);
            Message::create($data);
            echo "私信已发送";
        }
        //
        return view("admin.sender");
    }

    public function taskpass(Request $request)
    {
        $input = $request->all();
        $username = $input['username'];
        $taskid = $input['taskid'];

        $userdata = DB::select("select id from users where name='" . $username . "'");
        if (count($userdata) < 1) return "未找到该用户";
        $userid = $userdata[0]->id;

        $taskdata = DB::select("select id from tasks where id=" . $taskid);
        if (count($taskdata) < 1) return "未找到该题目";

        $passcnt = DB::select("select count(*) as cnt from solves where userid=" . $userid . " and taskid=" . $taskid . " and type=0");
        if ($passcnt[0]->cnt < 1) {
            $solve = array();
            $solve['userid'] = $userid;
            $solve['taskid'] = $taskid;
            $solve['type'] = 0;
            $solve['created_at'] = date("Y-m-d H:i:s");
            $data = Solve::create($solve);
            return "该用户的该题从未通过变为通过！";
        } else return "该用户的该题已经答对过，不需要设置";
    }

    public function medalgrant(Request $request)
    {
        $input = $request->all();
        $username = $input['username'];
        $class = $input['class'];
        if (isset($input['title'])) $title = $input['title'];
        if (isset($input['userid'])) $userid = $input['userid'];
        if (empty($userid)) {
            $userdata = User::where(['name' => $username])->first();
            if (count($userdata) == 0) return "未找到该用户";
            $userid = $userdata[0]->id;
        }

        $cntdata = Medal::where(['userid' => $userid, 'class' => $class])->first();
        if (count($cntdata) > 0) return "该用户已经发了该勋章，无需重发！";

        $titledata = Medal::where(['class' => $class])->orderBy('id')->first();
        if (count($titledata) > 0) $title = $titledata[0]->title;

        if (empty($title)) return "此次title不能为空，请传入";

        $medaldata = array();
        $medaldata['userid'] = $userid;
        $medaldata['class'] = $class;
        $medaldata['title'] = $title;
        $aa = Medal::create($medaldata);

        return "勋章发放成功！";
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request $request
     * @param  int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}
